package com.zntg.schedule;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zntg.bo.FundFeneSureBook;
import com.zntg.bo.TCustBuyinBo;
import com.zntg.bo.TSpciProdBo;
import com.zntg.contants.FundFeneSureBookContants;
import com.zntg.entity.*;
import com.zntg.mapper.crmdb.TblobtSorageMapper;
import com.zntg.mapper.odsdb.KaiFangShiChanPinMapper;
import com.zntg.mapper.odsdb.TCustBuyinMapper;
import com.zntg.mapper.odsdb.TLogContractGetMapper;
import com.zntg.mapper.odsdb.TSpciProdMapper;
import com.zntg.pdf.CreatePdfUtilTemplate1;
import com.zntg.utils.ComponentFactory;
import com.zntg.utils.DateUtils;
import com.zntg.utils.string.StringUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.*;

/**
 * 对应ods库T_SPCI_PROD这张表的SPCI_TYE = '1'的份额确认书生成功能
* @Description: 开放式产品生成认购书功能
* @Author: zhengyunfei
* @Date: 2019/6/21
* @time:13:21
*/
@Component
public class Template1ScheduledTask {
    @Value("${server.port}")
    String port;
    /**电子签章生成路径*/
    @Value("${template.targetPath}")
    String targetPath;
    private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(Template1ScheduledTask.class);


    /**
     * 每隔5秒执行, 单位：ms。
     */
  /*  @Scheduled(fixedRate = 5000)
    public void testFixRate() {
        System.out.println("我每隔5秒冒泡一次：" + dateFormat.format(new Date()));
        Logger.info("打印当前时间: {}.", dateFormat.format(new Date()));
    }*/

  @Scheduled(cron = "0 0 1 * * ?")   //每天凌晨1点执行
  /* @Scheduled(cron = "0 0/1 * * * ?") */   //每5分钟一次
   /*@Scheduled(fixedRate = 50000)*/
    public void task1() {
        try {
            System.out.println("Template1ScheduledTask开放式产品计划任务开始执行，规则5分钟每天凌晨1点，当前执行时间==="+ DateUtils.getCurrentDate());
            KaiFangShiChanPinMapper kaiFangShiChanPinMapper = ComponentFactory.getBean(KaiFangShiChanPinMapper.class);
            TCustBuyinMapper tCustBuyinMapper = ComponentFactory.getBean(TCustBuyinMapper.class);
            TblobtSorageMapper tblobtSorageMapper = ComponentFactory.getBean(TblobtSorageMapper.class);
            TLogContractGetMapper tLogContractGetMapper = ComponentFactory.getBean(TLogContractGetMapper.class);
            TSpciProdMapper tSpciProdMapper = ComponentFactory.getBean(TSpciProdMapper.class);
            List<TCustBuyinEntity> list = kaiFangShiChanPinMapper.findAllCreateSign();
            List<FundFeneSureBook> fundFeneSureBookList=null;
            Gson gson=new Gson();
            if(list.size()>0){
                System.out.println("开放式产品需要生成认购书的总数===================================="+list.size());
                fundFeneSureBookList=new ArrayList<>();
                for(int i=0;i<list.size();i++){
                    TCustBuyinEntity custBuyinEntity=list.get(i);
                    System.out.println("认购书信息==========="+gson.toJson(custBuyinEntity));
                    TCustBuyinBo custBuyinBo= TCustBuyinBo.entityToBo(custBuyinEntity);
                    FundFeneSureBook fundFeneSureBook=TCustBuyinBo.getFeneBook(custBuyinBo);
                    //根据产品编号查询生成的认购书或者追加书模板的名称，配置在T_SPCI_PROD表里面，此外需要将模板放在项目service_electronic_signatu的reresources下面
                    String prodId=custBuyinEntity.getProdId();
                    TSpciProdBo tSpciProdBo=new TSpciProdBo();
                    tSpciProdBo.setProdId(prodId);
                    TSpciProdEntity tSpciProdEntity=tSpciProdMapper.findByBo(tSpciProdBo);
                    if(!StringUtils.isEmpty(tSpciProdEntity)){
                        //返回的需要生成认购书的类型，01表示生成申购书，02，表示生成追加书
                        String cyType=fundFeneSureBook.getCyType();
                        //即要生成申购书，又要生成追加书，具体什么哪个，根据cyType判断，如果cyType=1,生成申购书，如果cyType=1,生成追加书
                        String cCustType=custBuyinEntity.getcCustType();//0：企业 1：个人 新增字段
                        System.out.println("开放式认购书类型cCustType========================="+cCustType);
                        //申购书
                        if(FundFeneSureBookContants.CON_TYP_STATUS_1.equals(cyType)||FundFeneSureBookContants.CON_TYP_STATUS_01.equals(cyType)){
                            if("0".equals(cCustType)){
                                fundFeneSureBook.setSourcePath(tSpciProdEntity.getPurLettComp());//企业
                            }else {
                                fundFeneSureBook.setSourcePath(tSpciProdEntity.getPurLett());//个人
                            }
                        }
                        //追加书
                        if(FundFeneSureBookContants.CON_TYP_STATUS_2.equals(cyType)||FundFeneSureBookContants.CON_TYP_STATUS_02.equals(cyType)){
                            if("0".equals(cCustType)){
                                fundFeneSureBook.setSourcePath(tSpciProdEntity.getAddPurLettComp());//企业追加认购书
                            }else {
                                fundFeneSureBook.setSourcePath(tSpciProdEntity.getAddPurLett());//个人追加
                            }

                        }
                    }
                    //查询crm附件序号
                    String lStorageid=tblobtSorageMapper.getTblobStorageSeq()+"";
                    fundFeneSureBook.setlStorageid(lStorageid);
                    fundFeneSureBookList.add(fundFeneSureBook);
                }
                //start ****************
                String jsonData= gson.toJson(fundFeneSureBookList);
                String resultJson=getCreateJson(jsonData);
                //处理返回结果
                List <FundFeneSureBook> resultBackList=gson.fromJson(resultJson,new TypeToken<List<FundFeneSureBook>>(){}.getType());
                //定时任务可以做耗时操作，包括做生成数据库报表、文件IO等等需要定时执行的逻辑
                if (list != null) {
                    System.out.println("一共多少条数据======================"+list.size());
                    for(int i=0;i<resultBackList.size();i++){
                        FundFeneSureBook fundFeneSureBook=resultBackList.get(i);
                        //更新状态
                        String pkId=fundFeneSureBook.getPkId();
                        String storId=fundFeneSureBook.getlStorageid();
                        String cSubkeyId=fundFeneSureBook.getcSubkeyId();
                        TCustBuyinEntity updateParam=new TCustBuyinEntity();
                        updateParam.setPkId(pkId);
                        updateParam.setContractId("Y");
                        tCustBuyinMapper.update(updateParam);
                        System.out.println("定时任务执行job"+(i+1)+":更新任务书状态ok" );
                        //插入日志
                        LogContractGetEntity logContractGetBo=new LogContractGetEntity();
                        logContractGetBo.setBuyinPkId(pkId);
                        logContractGetBo.setStorId(storId);
                        //系统日期 YYMMDD
                        tLogContractGetMapper.add(logContractGetBo);
                        System.out.println("定时任务执行job"+(i+1)+":插入日志ok" );
                        //生成附件表到Crmku
                        TblobstorageNewEntity tblobstorageBo=new TblobstorageNewEntity();
                        Map<String,Object>  insertMap=new HashMap<>();

                        tblobstorageBo.setlStorageid(storId+"");
                        //合同号
                        String htNo=fundFeneSureBook.getHtNo();
                        tblobstorageBo.setcNodecode(htNo);
                        //生成的文件名
                        String fileName=fundFeneSureBook.getFileName();
                        String fileSize=fundFeneSureBook.getFileSize();
                        tblobstorageBo.setcFilename(fileName);
                        tblobstorageBo.setlFilesize(fileSize);
                        tblobstorageBo.setcSubkeyid(cSubkeyId);
                        insertMap.put("lStorageid",storId+"");
                        insertMap.put("cNodecode",htNo);
                        insertMap.put("cFilename",fileName);
                        insertMap.put("lFileSize",fileSize);
                        insertMap.put("cSubkeyid",cSubkeyId);
                        tblobtSorageMapper.addMap(insertMap);
                        System.out.println("定时任务执行job"+(i+1)+":生成crm附件表ok========Template1ScheduledTask" );
                    }
                    System.out.println(list.size()+"条任务处理完成");

                } else {
                    System.out.println("我什么事都不用做，等待下次再说吧");
                }
                //end ****************
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {

        }
    }
    public String getCreateJson( String  jsonData ){
        //生成电子签章
        String resultJson="";
        try {
            System.out.println("开放式产品生成认购书参数==============="+jsonData);
            //将json转换为list
            Gson gson=new Gson();
            List <FundFeneSureBook> list=gson.fromJson(jsonData,new TypeToken<List<FundFeneSureBook>>(){}.getType());
            List <FundFeneSureBook> result=new ArrayList<>();
            if(null!=list){
                for(int i=0;i<list.size();i++){
                    FundFeneSureBook fundFeneSureBook=list.get(i);
                    String cyType=fundFeneSureBook.getCyType();
                    System.out.println("确认书类型========================="+cyType);
                    if(!StringUtil.isNullOrEmpty(cyType)){
                        fundFeneSureBook.setTargetPath(targetPath);
                        System.out.println("SourcePath========================="+fundFeneSureBook.getSourcePath());
                        System.out.println("targetPath========================="+fundFeneSureBook.getTargetPath());
                        FundFeneSureBook resultBo= CreatePdfUtilTemplate1.createPdfJingZhiLei(fundFeneSureBook);
                        result.add(resultBo);
                    }
                }
                resultJson=gson.toJson(result);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return resultJson;
    }
}

